export const formatTime = date => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  );
};

export const formatNumber = n => {
  n = n.toString();
  return n[1] ? n : '0' + n;
}; // 计算这个月有多少天

export function getCurrentMonthDayNum() {
  let today = new Date();
  let dayAllThisMonth = 31;

  if (today.getMonth() + 1 != 12) {
    let currentMonthStartDate = new Date(
      today.getFullYear() + '/' + (today.getMonth() + 1) + '/01'
    ); // 本月1号的日期

    let nextMonthStartDate = new Date(
      today.getFullYear() + '/' + (today.getMonth() + 2) + '/01'
    ); // 下个月1号的日期

    dayAllThisMonth =
      (nextMonthStartDate - currentMonthStartDate) / (24 * 3600 * 1000);
  }
  return dayAllThisMonth;
}

export function showToast(text) {
  uni.showToast({
    title: text ? text : '',
    icon: 'none',
    duration: 3000,
  });
}

export function showLoading(text) {
  uni.showLoading({
    title: text ? text : '正在加载',
  });
}

export function hideLoading() {
  uni.hideLoading({
    success: res => {},
    fail: res => {},
    complete: res => {},
  });
}

export function filterParams(obj) {
  var _newPar = {};
  for (var key in obj) {
    // 如果对象属性的值不为空，就保存该属性（这里我做了限制，如果属性的值为0，保存该属性。如果属性的值全部是空格，属于为空。
    if (
      (obj[key] === 0 || obj[key] === false || obj[key]) &&
      obj[key].toString().replace(/(^\s*)|(\s*$)/g, '') !== ''
    ) {
      _newPar[key] = obj[key];
    }
  }
  return _newPar;
}

// 图片地址处理
export function processingImgUrl(url) {
  if (!url) {
    return '';
  }
  if (url.includes('http://') || url.includes('https://')) {
    return url;
  }
  return `https://file.diqihengrun.com/image${url}`;
}

export function keepTwoDecimalFull(num) {
  var result = parseFloat(num);
  if (isNaN(result)) {
    console.log('传递参数错误，请检查！');
    return false;
  }
  result = Math.round(num * 100) / 100;
  var s_x = result.toString(); //将数字转换为字符串

  var pos_decimal = s_x.indexOf('.'); //小数点的索引值

  // 当整数时，pos_decimal=-1 自动补0
  if (pos_decimal < 0) {
    pos_decimal = s_x.length;
    s_x += '.';
  }

  // 当数字的长度< 小数点索引+2时，补0
  while (s_x.length <= pos_decimal + 2) {
    s_x += '0';
  }
  return s_x;
}

/** 手机号校验
 * @param {Array} phone
 * @returns {Boolean}
 */
export function checkPhone(phone) {
  if (/^1(3|4|5|6|7|8|9)\d{9}$/.test(phone)) {
    return true;
  }
  return false;
}

// 金额格式化——显示千位分隔符
export function priceFormat(num) {
  let str = num.toString();
  // 没有小数点时，在末尾补上一个小数点
  if (str.indexOf('.') === -1) {
    str += '.';
  }
  return str.replace(/(\d)(?=(\d{3})+\.)/g, '$1,').replace(/\.$/, '');
}

/**
 * 节流
 * @param {function} func 方法
 * @param {number} delay 时间
 * @returns
 */
export function throttle(func, delay) {
  var timer = null;
  return function () {
    var context = this;
    var args = arguments;
    if (!timer) {
      timer = setTimeout(function () {
        func.apply(context, args);
        timer = null;
      }, delay);
    }
  };
}

/**
 * 数字转成汉字
 * @params num === 要转换的数字
 * @return 汉字
 * */
function toChineseNum(num) {
  let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  let unit = ['', '十', '百', '千', '万'];
  num = parseInt(num);
  let getWan = temp => {
    let strArr = temp.toString().split('').reverse();
    let newNum = '';
    let newArr = [];
    strArr.forEach((item, index) => {
      newArr.unshift(
        item === '0' ? changeNum[item] : changeNum[item] + unit[index]
      );
    });
    let numArr = [];
    newArr.forEach((m, n) => {
      if (m !== '零') numArr.push(n);
    });
    if (newArr.length > 1) {
      newArr.forEach((m, n) => {
        if (newArr[newArr.length - 1] === '零') {
          if (n <= numArr[numArr.length - 1]) {
            newNum += m;
          }
        } else {
          newNum += m;
        }
      });
    } else {
      newNum = newArr[0];
    }

    return newNum;
  };
  let overWan = Math.floor(num / 10000);
  let noWan = num % 10000;
  if (noWan.toString().length < 4) {
    noWan = '0' + noWan;
  }
  return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num);
}

export function getWxToken() {
  var token = '';
  if (uni.getStorageSync('token')) {
    token = uni.getStorageSync('token');
    return token;
  }
  return token;
}

